package com.uzai.console.service.groupsendjob.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.taobao.api.internal.toplink.embedded.websocket.util.StringUtil;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.enums.GroupSendStatusEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ESResult;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.feign.groupsendjob.GroupSendJobIdFeignDto;
import com.uzai.console.dto.groupsendjob.GroupSendJobIdDto;
import com.uzai.console.dto.groupsendjob.GroupSendJobQuery;
import com.uzai.console.dto.groupsendjob.GroupSendJobUpdateDto;
import com.uzai.console.dto.groupsendjob.GroupSendJobUserQueryParaDto;
import com.uzai.console.dto.groupsendjobdetail.*;
import com.uzai.console.entity.Device;
import com.uzai.console.entity.DeviceWechatInfo;
import com.uzai.console.entity.GroupSendJob;
import com.uzai.console.entity.Merchant;
import com.uzai.console.entity.es.EsGroupSendMsg;
import com.uzai.console.entity.es.PyqJobDetail;
import com.uzai.console.entity.es.WechatBlacklistPub;
import com.uzai.console.enums.GroupSendJobSourceEnum;
import com.uzai.console.mapper.GroupSendJobMapper;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.feign.UzaiBroadcastFeignService;
import com.uzai.console.service.groupsendjob.GroupSendJobDetailService;
import com.uzai.console.service.groupsendjob.GroupSendJobService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.vo.device.DeviceInfoVo;
import com.uzai.console.vo.groupsendjob.GroupSendJobInfoVo;
import com.uzai.console.vo.groupsendjob.GroupSendJobSendErrInfoVo;
import com.uzai.console.vo.groupsendjob.GroupSendJobSubVo;
import com.uzai.console.vo.groupsendjob.GroupSendMsgVo;
import com.uzai.console.vo.pyq.pyqjobdetail.PyqJobDetailVo;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 群发任务
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class GroupSendJobDetailServiceImpl implements GroupSendJobDetailService {

    Logger logger = LoggerFactory.getLogger(GroupSendJobDetailServiceImpl.class);

    @Autowired
    private GroupSendJobMapper groupSendJobMapper;

    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;
    @Autowired
    private UzaiBroadcastFeignService uzaiBroadcastFeignService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private MerchantService merchantService;


    /**
     * 查询群发子任务列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param groupSendJobSubQuery
     * @return null
     */
    public Page<GroupSendJobSubVo> findGroupSendJobSubList(GroupSendJobSubQuery groupSendJobSubQuery){

        if(groupSendJobSubQuery.getParentId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入主任务id");
        }

        Integer now = DateUtil.getNowTime();

        //新建返回到页面的LIST对象
        List<GroupSendJobSubVo> groupSendJobSubVoList = new ArrayList<>();

        //执行分页查询对象
        Page<GroupSendJob> page = new Page<>();
        groupSendJobSubQuery.convert(page);

        GroupSendJobQuery groupSendJobQuery = new GroupSendJobQuery();
        BeanUtils.copyProperties(groupSendJobSubQuery, groupSendJobQuery);
        groupSendJobQuery.setMerId(groupSendJobSubQuery.getMerId());
        groupSendJobQuery.setParentId(groupSendJobSubQuery.getParentId());
        List<GroupSendJob> groupSendJobList = groupSendJobMapper.findByList(page, groupSendJobQuery);
        if(groupSendJobList != null){
            for (GroupSendJob groupSendJob : groupSendJobList){
                GroupSendJobSubVo groupSendJobSubVo = new GroupSendJobSubVo();
                BeanUtils.copyProperties(groupSendJob, groupSendJobSubVo);

                //如果完成发送总数大于预计发送总数，则预计发送总数显示为完成发送总数
                if(Tools.getInteger(groupSendJob.getFinishCount()).intValue() >= Tools.getInteger(groupSendJob.getTotalCount()).intValue()){
                    groupSendJobSubVo.setTotalCount(groupSendJob.getFinishCount());
                }

                //查询群发类型名称
                if(StringUtils.isNotBlank(groupSendJob.getDeviceType())){
                    DeviceTypeEnum deviceTypeEnum = DeviceTypeEnum.getByKey(groupSendJob.getDeviceType());
                    if(deviceTypeEnum != null){
                        groupSendJobSubVo.setDeviceTypeName(deviceTypeEnum.getRemark());
                    }
                }

                //标签
                if(StringUtils.isNotBlank(groupSendJob.getUserLab())){
                    groupSendJobSubVo.setUserLabList(JSONObject.parseArray(groupSendJob.getUserLab(), String.class));
                }

                //群发来源
                if(groupSendJobSubVo.getSource() != null){
                    GroupSendJobSourceEnum groupSendJobSourceEnum = GroupSendJobSourceEnum.getById(groupSendJobSubVo.getSource());
                    if(groupSendJobSourceEnum != null){
                        groupSendJobSubVo.setSourceName(groupSendJobSourceEnum.getDesc());
                    }
                }

                //屏蔽关键字
                if(StringUtils.isNotBlank(groupSendJob.getIgnore())){
                    groupSendJobSubVo.setIgnoreList(JSONObject.parseArray(groupSendJob.getIgnore(), String.class));
                }

                //屏蔽昵称关键字
                if(StringUtils.isNotBlank(groupSendJob.getIgnoreName())){
                    groupSendJobSubVo.setIgnoreNameList(JSONObject.parseArray(groupSendJob.getIgnoreName(), String.class));
                }

                //屏蔽备注关键字
                if(StringUtils.isNotBlank(groupSendJob.getIgnoreRemark())){
                    groupSendJobSubVo.setIgnoreRemarkList(JSONObject.parseArray(groupSendJob.getIgnoreRemark(), String.class));
                }

                Device device = deviceService.findDeviceInfoByDeviceUniqueId(groupSendJob.getDeviceUniqueId(), null, groupSendJob.getMerId());
                if(device != null){
                    groupSendJobSubVo.setDeviceUniqueId(groupSendJob.getDeviceUniqueId());
                    groupSendJobSubVo.setDeviceId(device.getDeviceId());
                    groupSendJobSubVo.setDeviceName(device.getDeviceName());
                    groupSendJobSubVo.setDeviceRemark(device.getDeviceRemark());
                }

                //查询发送失败数
                if(StringUtils.isNotBlank(groupSendJob.getSendErrInfo())){
                    try{
                        GroupSendJobSendErrInfoVo sendErrInfoVo_sun = JSONObject.parseObject(groupSendJob.getSendErrInfo(), GroupSendJobSendErrInfoVo.class);
                        if(sendErrInfoVo_sun != null){
                            groupSendJobSubVo.setSendErrInfo(sendErrInfoVo_sun);
                            groupSendJobSubVo.setSendErrTotal(sendErrInfoVo_sun.getTotal());
                        }
                    }catch (Exception e){}
                }

                if(StringUtils.isNotBlank(groupSendJob.getUserQueryPara())){
                    try{
                        GroupSendJobUserQueryParaDto userQueryParaDto = JSONObject.parseObject(groupSendJob.getUserQueryPara(), GroupSendJobUserQueryParaDto.class);
                        groupSendJobSubVo.setUserQueryParaDto(userQueryParaDto);
                    }catch (Exception e){}
                }

                groupSendJobSubVoList.add(groupSendJobSubVo);
            }
        }

        //返回到页面分页对象
        Page<GroupSendJobSubVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(groupSendJobSubVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询群发子任务详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param groupSendJobSubIdDto
     * @return null
     */
    public GroupSendJobSubVo findGroupSendJobSub(GroupSendJobSubIdDto groupSendJobSubIdDto){
        //返回到页面的VO对象
        GroupSendJobSubVo groupSendJobSubVo = new GroupSendJobSubVo();

        if(groupSendJobSubIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }

        GroupSendJob groupSendJob = groupSendJobMapper.selectById(groupSendJobSubIdDto.getId(), groupSendJobSubIdDto.getMerId());

        if(groupSendJob == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        //将查询到的数据复制到页面VO中
        BeanUtils.copyProperties(groupSendJob, groupSendJobSubVo);

        //查询群发类型名称
        if(StringUtils.isNotBlank(groupSendJob.getDeviceType())){
            DeviceTypeEnum deviceTypeEnum = DeviceTypeEnum.getByKey(groupSendJob.getDeviceType());
            if(deviceTypeEnum != null){
                groupSendJobSubVo.setDeviceTypeName(deviceTypeEnum.getRemark());
            }
        }

        //标签
        if(StringUtils.isNotBlank(groupSendJob.getUserLab())){
            groupSendJobSubVo.setUserLabList(JSONObject.parseArray(groupSendJob.getUserLab(), String.class));
        }

        //群发来源
        if(groupSendJobSubVo.getSource() != null){
            GroupSendJobSourceEnum groupSendJobSourceEnum = GroupSendJobSourceEnum.getById(groupSendJobSubVo.getSource());
            if(groupSendJobSourceEnum != null){
                groupSendJobSubVo.setSourceName(groupSendJobSourceEnum.getDesc());
            }
        }

        //屏蔽关键字
        if(StringUtils.isNotBlank(groupSendJob.getIgnore())){
            groupSendJobSubVo.setIgnoreList(JSONObject.parseArray(groupSendJob.getIgnore(), String.class));
        }

        //屏蔽昵称关键字
        if(StringUtils.isNotBlank(groupSendJob.getIgnoreName())){
            groupSendJobSubVo.setIgnoreNameList(JSONObject.parseArray(groupSendJob.getIgnoreName(), String.class));
        }

        //屏蔽备注关键字
        if(StringUtils.isNotBlank(groupSendJob.getIgnoreRemark())){
            groupSendJobSubVo.setIgnoreRemarkList(JSONObject.parseArray(groupSendJob.getIgnoreRemark(), String.class));
        }

        Device device = deviceService.findDeviceInfoByDeviceUniqueId(groupSendJob.getDeviceUniqueId(), null, groupSendJob.getMerId());
        if(device != null){
            groupSendJobSubVo.setDeviceUniqueId(groupSendJob.getDeviceUniqueId());
            groupSendJobSubVo.setDeviceId(device.getDeviceId());
            groupSendJobSubVo.setDeviceName(device.getDeviceName());
            groupSendJobSubVo.setDeviceRemark(device.getDeviceRemark());
        }

        //查询发送失败数
        if(StringUtils.isNotBlank(groupSendJob.getSendErrInfo())){
            try{
                GroupSendJobSendErrInfoVo sendErrInfoVo_sun = JSONObject.parseObject(groupSendJob.getSendErrInfo(), GroupSendJobSendErrInfoVo.class);
                if(sendErrInfoVo_sun != null){
                    groupSendJobSubVo.setSendErrInfo(sendErrInfoVo_sun);
                    groupSendJobSubVo.setSendErrTotal(sendErrInfoVo_sun.getTotal());
                }
            }catch (Exception e){}
        }

        if(StringUtils.isNotBlank(groupSendJob.getUserQueryPara())){
            try{
                GroupSendJobUserQueryParaDto userQueryParaDto = JSONObject.parseObject(groupSendJob.getUserQueryPara(), GroupSendJobUserQueryParaDto.class);
                groupSendJobSubVo.setUserQueryParaDto(userQueryParaDto);
            }catch (Exception e){}
        }

        return  groupSendJobSubVo;
    }

    /**
     * 修改群发子任务开始时间
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param groupSendJobSubUpdateDto
     * @return null
     */
    @Transactional
    public void updateGroupSendJobSub(GroupSendJobSubUpdateDto groupSendJobSubUpdateDto){
        if(groupSendJobSubUpdateDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入子任务id");
        }

        GroupSendJob groupSendJob = groupSendJobMapper.selectById(groupSendJobSubUpdateDto.getId(), groupSendJobSubUpdateDto.getMerId());

        if(groupSendJob == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        if(groupSendJob.getStatus().intValue() == GroupSendStatusEnum.FINISH.getValue().intValue()
                || groupSendJob.getStatus().intValue() == GroupSendStatusEnum.INVALID.getValue().intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "已完成或者过期的任务不能修改");
        }

        String content = groupSendJobSubUpdateDto.getContent();
        if(StringUtils.isBlank(content)){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "消息内容不能为空");
        }
        //修改内容
        groupSendJob.setContent(Tools.getStr(content));

        Integer now = DateUtil.getNowTime();

        //未开始任务可以修改开始时间
        if(groupSendJob.getStatus().intValue() == GroupSendStatusEnum.NOT_START.getValue().intValue()){

            Integer beginTime = groupSendJobSubUpdateDto.getBeginTime();
            if(beginTime == null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "开始时间不能为空");
            }

            if(beginTime-now < 0){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "开始时间不能小于当前时间");
            }

            if(beginTime-groupSendJob.getCreateTime() > 7*24*3600){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "开始时间必须在创建时间的7天之内");
            }

            groupSendJob.setBeginTime(beginTime);
            groupSendJob.setEndTime(groupSendJobSubUpdateDto.getEndTime());
            groupSendJob.setSendStartTime(beginTime);
        }
        groupSendJob.setUpdateTime(now);
        //修改子任务
        groupSendJobMapper.updateByIdSelective(groupSendJob);
    }

    /**
     * 开始群发子任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param groupSendJobSubIdDto
     * @return null
     */
    @Transactional
    public void startGroupSendJobSub(GroupSendJobSubIdDto groupSendJobSubIdDto){
        if(groupSendJobSubIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        GroupSendJob groupSendJob = groupSendJobMapper.selectById(groupSendJobSubIdDto.getId(), groupSendJobSubIdDto.getMerId());

        if(groupSendJob == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        if(groupSendJob.getStatus().intValue() != GroupSendStatusEnum.NOT_START.getValue().intValue() && groupSendJob.getStatus().intValue() != GroupSendStatusEnum.PAUSE.getValue().intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只有未开始或暂停任务才能开启");
        }

        Integer now = DateUtil.getNowTime();

        if(groupSendJob.getStatus().intValue() == GroupSendStatusEnum.NOT_START.getValue().intValue()){ //未开始的任务，将开始时间设置成当前时间
            groupSendJob.setBeginTime(now);
            groupSendJob.setSendStartTime(now);
        }else{ //暂停的任务，延迟5分钟咋发送
            groupSendJob.setBeginTime(now+60*5);
            groupSendJob.setSendStartTime(now+60*5);//延迟5分钟
        }

        groupSendJob.setStatus(GroupSendStatusEnum.RUNNING.getValue().intValue());
        groupSendJob.setUpdateTime(now);
        groupSendJob.setFinishCountSnapshot(groupSendJob.getFinishCount());

        //从ES中获取该子任务的已发送数
//        GroupSendJobIdFeignDto groupSendJobIdFeignDto = new GroupSendJobIdFeignDto();
//        groupSendJobIdFeignDto.setId(groupSendJob.getId());
//        UzaiRespVo<Integer> uzaiRespVo = uzaiBroadcastFeignService.groupSendFinishCount(groupSendJobIdFeignDto);
//        if(uzaiRespVo != null && uzaiRespVo.getCode() == 200){
//            if(Tools.getInteger(uzaiRespVo.getData()).intValue() != 0){
//                groupSendJob.setFinishCountSnapshot(uzaiRespVo.getData());
//            }
//        }
        groupSendJobMapper.updateByIdSelective(groupSendJob);
    }

    /**
     * 暂停群发子任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param groupSendJobSubIdDto
     * @return null
     */
    @Transactional
    public void pauseGroupSendJobSub(GroupSendJobSubIdDto groupSendJobSubIdDto){
        if(groupSendJobSubIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        GroupSendJob groupSendJob = groupSendJobMapper.selectById(groupSendJobSubIdDto.getId(), groupSendJobSubIdDto.getMerId());

        if(groupSendJob == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        if(groupSendJob.getStatus().intValue() != GroupSendStatusEnum.RUNNING.getValue().intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只有进行中任务才能暂停");
        }

        Integer now = DateUtil.getNowTime();
        groupSendJob.setStatus(GroupSendStatusEnum.PAUSE.getValue().intValue());
        groupSendJob.setUpdateTime(now);
        groupSendJobMapper.updateById(groupSendJob);
    }

    /**
     * 结束群发子任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param groupSendJobSubIdDto
     * @return null
     */
    @Transactional
    public void finishGroupSendJobSub(GroupSendJobSubIdDto groupSendJobSubIdDto){
        if(groupSendJobSubIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        GroupSendJob groupSendJob = groupSendJobMapper.selectById(groupSendJobSubIdDto.getId(), groupSendJobSubIdDto.getMerId());

        if(groupSendJob == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        if(groupSendJob.getStatus().intValue() != GroupSendStatusEnum.RUNNING.getValue().intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只有进行中任务才能结束");
        }

        Integer now = DateUtil.getNowTime();
        groupSendJob.setStatus(GroupSendStatusEnum.FINISH.getValue().intValue());
        groupSendJob.setUpdateTime(now);
        groupSendJobMapper.updateById(groupSendJob);

    }

    /**
     * 删除群发子任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param groupSendJobSubIdDto
     * @return null
     */
    @Transactional
    public void deleteGroupSendJobSub(GroupSendJobSubIdDto groupSendJobSubIdDto){
        if(groupSendJobSubIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        GroupSendJob groupSendJob = groupSendJobMapper.selectById(groupSendJobSubIdDto.getId(), groupSendJobSubIdDto.getMerId());

        if(groupSendJob == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        //记录该子任务的消息数
        int msgNumSub = groupSendJob.getTotalCount();

        //删除子任务
        groupSendJobMapper.deleteById(groupSendJob.getId(), groupSendJobSubIdDto.getMerId());

        //删除群发任务ES数据
        DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest();
        deleteByQueryRequest.setQuery(new TermQueryBuilder("childJobId", groupSendJob.getId()));

        //查询运营商其他索引分片
        String uzai_group_send_msg = merchantService.getMechantOtherEsIndexName(EsIndexName.GROUP_SEND_MSG, groupSendJobSubIdDto.getMerId());
        elasticsearchUtilGroupMsg.deleteDataByQuerySingle(uzai_group_send_msg, deleteByQueryRequest);

        //查询主任务
        GroupSendJob groupSendJobParent = groupSendJobMapper.selectById(groupSendJob.getParentId(), groupSendJob.getMerId());
        if(groupSendJobParent != null){
            //查询主任务消息总数
            Integer totalCountParent = Tools.getInteger(groupSendJobParent.getTotalCount());
            totalCountParent = totalCountParent - msgNumSub;
            //修改主任务消息总数
            if(totalCountParent < 0){
                totalCountParent = 0;
            }
            groupSendJobParent.setTotalCount(totalCountParent);
            groupSendJobMapper.updateByIdSelective(groupSendJobParent);
        }
    }

    /**
     * 查询群发消息列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param groupSendMsgQuery
     * @return null
     */
    public Page<GroupSendMsgVo> findGroupSendMsgList(GroupSendMsgQuery groupSendMsgQuery){

        if(groupSendMsgQuery.getChildJobId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入子任务id");
        }

        GroupSendJob groupSendJob_child = groupSendJobMapper.selectById(groupSendMsgQuery.getChildJobId(), groupSendMsgQuery.getMerId());
        if(groupSendJob_child == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该子任务不存在");
        }

        //子任务发送时间
        int sendStartTime = Tools.getInteger(groupSendJob_child.getSendStartTime());

        Integer now = DateUtil.getNowTime();

        //新建返回到页面的LIST对象
        List<GroupSendMsgVo> groupSendMsgVoList = new ArrayList<>();

        //执行分页查询对象
        Page<GroupSendMsgVo> page = new Page<>();
        groupSendMsgQuery.convert(page);

        //ES查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        //运营商ID
        boolQuery.must(QueryBuilders.termQuery("merId", groupSendMsgQuery.getMerId()));

        //子任务id
        if(groupSendMsgQuery.getChildJobId() != null){
            boolQuery.must(QueryBuilders.termQuery("childJobId", groupSendMsgQuery.getChildJobId()));
        }
        searchSourceBuilder.query(boolQuery);
        //排序
        if(groupSendMsgQuery.getOrderByField() != null) {
            searchSourceBuilder.sort(groupSendMsgQuery.getOrderByField(), groupSendMsgQuery.isAsc() ? SortOrder.ASC : SortOrder.DESC);
        }else if(groupSendMsgQuery.getOrderItemList() != null && groupSendMsgQuery.getOrderItemList().size() > 0){
            for (OrderItem orderItem : groupSendMsgQuery.getOrderItemList()) {
                searchSourceBuilder.sort(orderItem.getColumn(), orderItem.isAsc() ? SortOrder.ASC : SortOrder.DESC);
            }
        }else{
            searchSourceBuilder.sort("delay", SortOrder.ASC);
        }

        //查询运营商其他索引分片
        String uzai_group_send_msg = merchantService.getMechantOtherEsIndexName(EsIndexName.GROUP_SEND_MSG, groupSendMsgQuery.getMerId());
        ESResult esResult = elasticsearchUtilGroupMsg.searchListData(uzai_group_send_msg, searchSourceBuilder, groupSendMsgQuery.getSize(), groupSendMsgQuery.getFromIndex(), null, null, null, groupSendMsgQuery.getMerId());
        page.setTotal(esResult.getTotalHits());
        List<Map<String, Object>> dataList = esResult.getDataList();
        if(dataList != null && dataList.size() > 0){
            for (Map<String, Object> dataMp :dataList) {
                EsGroupSendMsg esGroupSendMsg  = JSONObject.parseObject(JSONObject.toJSONString(dataMp), EsGroupSendMsg.class);
                GroupSendMsgVo groupSendMsgVo = new GroupSendMsgVo();
                if(esGroupSendMsg != null){
                    BeanUtils.copyProperties(esGroupSendMsg, groupSendMsgVo);

                    //将子任务中的消息显示，消息中的内容已经弃用
                    groupSendMsgVo.setMsg(groupSendJob_child.getContent());

                    //消息的发送时间=子任务的发送时间+延迟数
                    groupSendMsgVo.setSendTime(sendStartTime + esGroupSendMsg.getDelay());

                    //群发消息类型(0-普通模式；1-群发助手）
                    groupSendMsgVo.setGroupSendType(groupSendJob_child.getGroupSendType());

                    groupSendMsgVoList.add(groupSendMsgVo);
                }
            }
        }
        page.setRecords(groupSendMsgVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return page;
    }

    /**
     * 查询群发消息详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param groupSendMsgIdDto
     * @return null
     */
    public GroupSendMsgVo findGroupSendMsg(GroupSendMsgIdDto groupSendMsgIdDto){
        //返回到页面的VO对象
        GroupSendMsgVo groupSendMsgVo = new GroupSendMsgVo();

        if(groupSendMsgIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }

        //查询运营商其他索引分片
        String uzai_group_send_msg = merchantService.getMechantOtherEsIndexName(EsIndexName.GROUP_SEND_MSG, groupSendMsgIdDto.getMerId());

        Map<String, Object> map = elasticsearchUtilGroupMsg.searchDataById(uzai_group_send_msg, groupSendMsgIdDto.getId(), null);
        if(map == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该消息不存在");
        }

        EsGroupSendMsg esGroupSendMsg  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), EsGroupSendMsg.class);
        if(esGroupSendMsg == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        GroupSendJob groupSendJob_child = groupSendJobMapper.selectById(esGroupSendMsg.getChildJobId(), esGroupSendMsg.getMerId());
        if(groupSendJob_child == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该子任务不存在");
        }

        //子任务发送时间
        int sendStartTime = Tools.getInteger(groupSendJob_child.getSendStartTime());

        if(esGroupSendMsg != null){
            BeanUtils.copyProperties(esGroupSendMsg, groupSendMsgVo);

            //将子任务中的消息显示，消息中的内容已经弃用
            groupSendMsgVo.setMsg(groupSendJob_child.getContent());

            //消息的发送时间=子任务的发送时间+延迟数
            groupSendMsgVo.setSendTime(sendStartTime + esGroupSendMsg.getDelay());

            //群发消息类型(0-普通模式；1-群发助手）
            groupSendMsgVo.setGroupSendType(groupSendJob_child.getGroupSendType());
        }

        return groupSendMsgVo;

    }

    /**
     * 修改群发消息开始时间
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param groupSendMsgUpdateDto
     * @return null
     */
    @Transactional
    public void updateGroupSendMsg(GroupSendMsgUpdateDto groupSendMsgUpdateDto){
        if(StringUtils.isBlank(groupSendMsgUpdateDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        //查询运营商其他索引分片
        String uzai_group_send_msg = merchantService.getMechantOtherEsIndexName(EsIndexName.GROUP_SEND_MSG, groupSendMsgUpdateDto.getMerId());
        Map<String, Object> map = elasticsearchUtilGroupMsg.searchDataById(uzai_group_send_msg, groupSendMsgUpdateDto.getId(), null);
        if(map == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该消息不存在");
        }
        EsGroupSendMsg esGroupSendMsg  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), EsGroupSendMsg.class);

        if(esGroupSendMsg == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        GroupSendJob groupSendJob = groupSendJobMapper.selectById(esGroupSendMsg.getChildJobId(), esGroupSendMsg.getMerId());

        if(groupSendJob == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该消息所在任务不存在");
        }

        if(groupSendJob.getStatus().intValue() != GroupSendStatusEnum.NOT_START.getValue().intValue()
            && groupSendJob.getStatus().intValue() != GroupSendStatusEnum.PAUSE.getValue().intValue()
        ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只有未开始或暂停任务才能修改消息发送时间");
        }

        int now = DateUtil.getNowTime();
        //未开始任务可以修改开始时间
        Integer beginTime = groupSendMsgUpdateDto.getBeginTime();
        if(beginTime == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "开始时间不能为空");
        }

        if(beginTime-now < 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "开始时间不能小于当前时间");
        }

        //计算发送消息延时数
        if(beginTime-groupSendJob.getCreateTime() > 7*24*3600){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "开始时间必须在创建时间的7天之内");
        }
        //延迟数=开始时间-子任务发送时间
        int delay = beginTime - groupSendJob.getSendStartTime();
        //修改消息发送时间
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("delay", delay); //延迟数
        elasticsearchUtilGroupMsg.updateDataById(jsonObject, uzai_group_send_msg, groupSendMsgUpdateDto.getId());
    }

    /**
     * 删除群发消息
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param groupSendMsgIdDto
     * @return null
     */
    @Transactional
    public void deleteGroupSendMsg(GroupSendMsgIdDto groupSendMsgIdDto){
        if(groupSendMsgIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        //查询运营商其他索引分片
        String uzai_group_send_msg = merchantService.getMechantOtherEsIndexName(EsIndexName.GROUP_SEND_MSG, groupSendMsgIdDto.getMerId());

        Map<String, Object> map = elasticsearchUtilGroupMsg.searchDataById(uzai_group_send_msg, groupSendMsgIdDto.getId(), null);
        if(map == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该消息不存在");
        }

        EsGroupSendMsg esGroupSendMsg  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), EsGroupSendMsg.class);
        if(esGroupSendMsg == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }
        //查询子任务
        GroupSendJob groupSendJob_child = groupSendJobMapper.selectById(esGroupSendMsg.getChildJobId(), esGroupSendMsg.getMerId());
        if(groupSendJob_child == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该消息所在子任务不存在");
        }

        if(groupSendJob_child.getStatus().intValue() != GroupSendStatusEnum.NOT_START.getValue().intValue()
            && groupSendJob_child.getStatus().intValue() != GroupSendStatusEnum.PAUSE.getValue().intValue()
        ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只有未开始任务或暂停任务才能删除消息");
        }

        //查询主任务
        GroupSendJob groupSendJob_parent = groupSendJobMapper.selectById(esGroupSendMsg.getParentJobId(), esGroupSendMsg.getMerId());
        if(groupSendJob_parent == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该消息所在主任务不存在");
        }
        //删除消息
        elasticsearchUtilGroupMsg.deleteDataById(uzai_group_send_msg, groupSendMsgIdDto.getId());

        //子任务总消息数
        Integer totalCount_child = Tools.getInteger(groupSendJob_child.getTotalCount());
        groupSendJob_child.setTotalCount(totalCount_child - 1);
        groupSendJobMapper.updateByIdSelective(groupSendJob_child);

        //修改主任务消息数
        Integer totalCount_parent = Tools.getInteger(groupSendJob_parent.getTotalCount());
        groupSendJob_parent.setTotalCount(totalCount_parent - 1);
        groupSendJobMapper.updateByIdSelective(groupSendJob_parent);

    }


}
